package com.maikang.exammall.repository;

import com.maikang.exammall.entity.User;
import com.maikang.exammall.entity.dto.promote.Client;
import com.maikang.exammall.entity.dto.user.UserProfileDTO;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserRepository extends BaseRepository<User, Long>, JpaSpecificationExecutor<User> {
    Optional<User> findByOpenId(String openId);
    User findByUnionId(String unionId);

    @Query("SELECT new com.maikang.exammall.entity.dto.user.UserProfileDTO(" +
            "user.id, " +
            "user.gender, " +
            "user.mobile, " +
            "user.username, " +
            "user.avatarUrl) " +
            "FROM User user " +
            "WHERE user.id = :userId ")
    UserProfileDTO findUserProfileById(@Param("userId") Long userId);

    Slice<Client> findByRefererIdOrderByCreatedDateDesc(Long refererId, Pageable pageable);

    @Query("SELECT user.id AS id, " +
            "user.username AS username," +
            " user.avatarUrl AS avatarUrl, u" +
            "ser.createdDate AS createdDate " +
            "FROM User user " +
            "INNER JOIN Order odr " +
            "ON user.id = odr.userId AND odr.isDeleted = 0 " +
            "AND odr.status BETWEEN :fromStatus AND :toStatus " +
            "WHERE user.refererId = :refererId ORDER BY user.createdDate DESC ")
    Slice<Client> findByRefererIdAndOrderStatus(@Param("refererId") Long refererId,
                                                   @Param("fromStatus") Integer fromStatus,
                                                   @Param("toStatus") Integer toStatus,
                                                   Pageable pageable);

    @Modifying
    @Query("UPDATE User user SET user.unsubscribed = TRUE WHERE user.openId = :openId")
    void unsubscribe(@Param("openId") String openId);
}
